package qeb.handheldmedical;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import qeb.handheldmedical.dialog.MultiDialog;
import qeb.handheldmedical.helper.PhoneInfo;
import qeb.handheldmedical.helper.WSHelper;
import qeb.handheldmedical.model.Phone;
import qeb.handheldmedical.model.User;

public class Login extends Activity {
    private Button btndelu; // 登录按钮
    private TextView login_name;// 登录工号
    private TextView login_password;// 登录密码
    private ImageView login_imgwait;
    private Dialog mDialog;
    private Handler handler = new Handler();
    private User usr = new User();
    private Phone phone = new Phone();
    public ProgressDialog pBar;
    private String isApply;
    private MultiDialog multiDialog;
    private String deviceId;
    private String newVerName;
    private int newVerCode;
    private String UpdateMessage;
    public static final String BAR_READ_ACTION = "SYSTEM_BAR_READ";// 条码广播
    public static final String RFID_READ_ACTION = "SYSTEM_RFID_READ";// RFID广播
    public static final String NLSCAN_SCANNER = "nlscan.action.SCANNER_RESULT";// 新大陆机型
    // honeywell
    private final static String TAG = "ScanResultReceiver";
    private static final String INTENT_ACTION_SCAN_RESULT = "com.honeywell.tools.action.scan_result";
    private static final String SCANACTION = "com.android.server.scannerservice.broadcastxhyy";// 小码哥
    private static final String Neusoft = "com.neusoft.action.scanner.read";// 东软
    public String action;// 扫描
    private BroadcastReceiver loginReciever;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        if (currentapiVersion > 13) {
            // TODO Auto-generated method stub
            // 由于安卓2.3版本以上SOAP协议严格要求要另开线程
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads().detectDiskWrites().detectNetwork()
                    .penaltyLog().build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()
                    .build());
        }
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.sys_login);
        initView();
        // readLoginHistory();
        initBarReciever();
    }

    private String getRunningActivityName() {

        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity = activityManager.getRunningTasks(1).get(0).topActivity
                .getShortClassName();
        return runningActivity.replace(".", "");
    }

    private void initBarReciever() {

        loginReciever = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                action = intent.getAction();
                Log.d("scan", "Login");
                String BAR_value = "";
                String STATE_value = "ok";

                if (action.equals(BAR_READ_ACTION)) {
                    BAR_value = intent.getStringExtra("BAR_VALUE");
                } else if (action.equals(RFID_READ_ACTION)) {
                    BAR_value = intent.getStringExtra("RFID_VALUE");
                } else if (action.equals(INTENT_ACTION_SCAN_RESULT)) {

                    if (intent.hasExtra("decode_rslt")) {
                        BAR_value = intent.getStringExtra("decode_rslt");
                    }

                } else if (action.equals(SCANACTION)) {
                    BAR_value = intent.getStringExtra("scannerdata")
                            .replaceAll("\r|\n", "");
                } else if (action.equals(Neusoft)) {
                    BAR_value = intent.getStringExtra("scanner_value")
                            .replaceAll("\r|\n", "");
                } else if (action.equals(NLSCAN_SCANNER)) {
                    STATE_value = intent.getStringExtra("SCAN_STATE");
                    BAR_value = TextUtils.isEmpty(intent.getStringExtra("SCAN_BARCODE1")) ? intent.getStringExtra("SCAN_BARCODE2") : intent.getStringExtra("SCAN_BARCODE1");
                    BAR_value = BAR_value.replaceAll("\r|\n", "");
                }

                if (!BAR_value.equals("ERROR") || STATE_value.equals("ok")) {// 扫描出错
                    String strGh = BAR_value.replace("GH", "");
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("gh", strGh);
                    map.put("pbh", "EMR");

                    JSONObject resultObject = WSHelper.getWebserviceJsonObject(
                            "Login4Scan", map);
                    if (resultObject != null) {
                        try {
                            final List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();

                            if (resultObject != null) {
                                usr.getValue(resultObject);
                                down();
                            } else {
                                Toast tt = Toast.makeText(Login.this,
                                        "工号不存在，请核对后重新扫描！", Toast.LENGTH_LONG);
                                tt.show();
                                tt.setGravity(Gravity.CENTER, 0, 0);
                            }
                        } catch (Exception e) {

                        }

                    } else {

                        Toast tt = Toast.makeText(Login.this,
                                "工号不存在，请核对后重新扫描！", Toast.LENGTH_LONG);
                        tt.show();
                        tt.setGravity(Gravity.CENTER, 0, 0);
                    }

                } else {
                    Toast tt = Toast.makeText(Login.this, "扫描出错！",
                            Toast.LENGTH_LONG);
                    tt.show();
                    tt.setGravity(Gravity.CENTER, 0, 0);
                }

            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(BAR_READ_ACTION);
        filter.addAction(RFID_READ_ACTION);
        filter.addAction(INTENT_ACTION_SCAN_RESULT);
        filter.addAction(SCANACTION);
        filter.addAction(Neusoft);
        filter.addAction(NLSCAN_SCANNER);
        registerReceiver(loginReciever, filter);

    }

    /**
     * 设置用户名与密码
     */
    private void readLoginHistory() {

        String dir = Environment.getExternalStorageDirectory() + "/"
                + "qebdown/LoginHistory.txt";

        StringBuffer sb = new StringBuffer();
        File file = new File(dir);
        try {
            FileInputStream fis = new FileInputStream(file);
            int c;
            while ((c = fis.read()) != -1) {
                sb.append((char) c);
            }
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String text = sb.toString();
        if (!text.equals("")) {
            try {
                JSONObject jsonData = new JSONObject(text);
                login_name.setText(jsonData.getString("userName"));
                login_password.setText(decrypt(jsonData.getString("passWord")));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

    private void WriteLoginHistory() {
        String dir = Environment.getExternalStorageDirectory() + "/"
                + "qebdown/";
        String fileName = "LoginHistory.txt";
        String str = "{\"userName\":\"" + login_name.getText().toString()
                + "\",\"passWord\":\""
                + encrypt(login_password.getText().toString()) + "\"}";
        writeTxtToFile(str, dir, fileName);

    }

    // 将字符串写入到文本文件中
    public void writeTxtToFile(String strcontent, String filePath,
                               String fileName) {
        // 生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent;
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                file.createNewFile();
            }

            FileOutputStream out = new FileOutputStream(file);
            out.write(strContent.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    /**
     * 用户名解密
     *
     * @param ssoToken 字符串
     * @return String 返回加密字符串
     */
    public String decrypt(String ssoToken) {
        try {
            String name = new String();
            java.util.StringTokenizer st = new java.util.StringTokenizer(
                    ssoToken, "%");
            while (st.hasMoreElements()) {
                int asc = Integer.parseInt((String) st.nextElement()) - 27;
                name = name + (char) asc;
            }

            return name;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 用户名加密
     *
     * @param ssoToken 字符串
     * @return String 返回加密字符串
     */
    public String encrypt(String ssoToken) {
        try {
            byte[] _ssoToken = ssoToken.getBytes("ISO-8859-1");
            String name = new String();
            // char[] _ssoToken = ssoToken.toCharArray();
            for (int i = 0; i < _ssoToken.length; i++) {
                int asc = _ssoToken[i];
                _ssoToken[i] = (byte) (asc + 27);
                name = name + (asc + 27) + "%";
            }
            return name;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 生成文件
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {

        }
    }

    // 初始化页面
    private void initView() {
        login_name = (TextView) findViewById(R.id.et_qqNum);
        login_password = (TextView) findViewById(R.id.et_qqPwd);
        btndelu = (Button) findViewById(R.id.btn_login);
        login_imgwait = (ImageView) findViewById(R.id.login_imgwait);
        login_imgwait.setImageResource(R.drawable.wait);
        btndelu.setOnClickListener(btndelu_OnClickListener);
        isApply = String.valueOf(getIntent().getSerializableExtra("isApply"));
        isApply = "1";// isApply.equals("1") ? "1" : "0";
    }

    private OnClickListener btndelu_OnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_login:
                    showRoundProcessDialog(Login.this, R.layout.wait);

                    break;
            }
        }
    };

    public void showRoundProcessDialog(Context mContext, int layout) {
        // Map<String, String> map = new HashMap<String, String>();
        // map.put("gh", login_name.getText().toString());
        // map.put("password", login_password.getText().toString());
        // OkGo.get(Urls.webModels("Login", map)).tag(this)
        // .execute(new StringCallback() {
        //
        // @Override
        // public void onSuccess(String arg0, Call arg1, Response arg2) {
        // // TODO Auto-generated method stub
        // Log.d("json", arg0);
        // }
        //
        // @Override
        // public void onBefore(BaseRequest request) {
        // // TODO Auto-generated method stub
        // super.onBefore(request);
        // }
        //
        // @Override
        // public void onAfter(String t, Exception e) {
        // // TODO Auto-generated method stub
        // super.onAfter(t, e);
        // }
        //
        // @Override
        // public void onError(Call call, Response response,
        // Exception e) {
        // // TODO Auto-generated method stub
        // super.onError(call, response, e);
        // }
        // });

        mDialog = new AlertDialog.Builder(mContext).create();
        mDialog.show();
        // 注意此处要放在show之后 否则会报异常
        mDialog.setContentView(layout);
        TextView txtmes = (TextView) mDialog.findViewById(R.id.textView1);
        txtmes.setText("正在登陆.....");
        doLogin(login_name.getText().toString(), login_password.getText()
                .toString());
        mDialog.cancel();
    }

    private void doLogin(final String gh, final String password) {
        new Thread() {
            public void run() {
                usr = WSHelper.Login(gh, password);
                down();
            }
        }.start();

    }

    private boolean IsUpdate() {
        boolean state = false;

        try {
            if (getServerVerCode()) {
                int vercode = WSHelper.getVerCode(this);
                if (newVerCode > vercode) {
                    doNewVersionUpdate();
                    state = true;
                } else {
                    state = false;
                }
            }
        } catch (Exception e) {

        }

        return state;

    }

    // 获取服务器版本号
    private boolean getServerVerCode() {
        int nowVerser = WSHelper.getVerCode(this);// 当前版本号

        String verjson = "";
        JSONObject obj = null;

        verjson = WSHelper.getContent(WSHelper.UPDATE_SERVER
                + WSHelper.UPDATE_VERJSON);
        // 老版本更新
        try {
            JSONArray array = new JSONArray(verjson);
            if (!array.equals(null) && array.length() > 0) {
                obj = array.getJSONObject(0);
                if (!obj.equals(null)) {
                    try {
                        newVerCode = Integer.parseInt(obj.getString("verCode"));
                        newVerName = obj.getString("verName");
                        UpdateMessage = "请稍等，正在更新中.....";
                    } catch (Exception e) {
                        newVerCode = -1;
                        newVerName = "";
                    }
                }
            }
        } catch (JSONException e1) { // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        return true;
    }

    // 与服务器版本号不想同，需要更新
    private void doNewVersionUpdate() {
        // int verCode = WSHelper.getVerCode(this);
        String verName = WSHelper.getVerName(this);
        StringBuffer sb = new StringBuffer();
        sb.append("当前版本:");
        sb.append(verName);
        // sb.append(" Code:");
        // sb.append(verCode);
        sb.append(", 发现新版本:");
        sb.append(newVerName);
        // sb.append(" Code:");
        // sb.append(newVerCode);
        sb.append(", 是否更新?\n\n");
        // sb.append("新版本更新内容：\n");
        // sb.append("1.优化患者信息页面。\n");
        // sb.append("2.修复“在院病人”、“出院病人”应网络差而引起的黑屏现象。\n");
        // sb.append("3.新增“病人信息”关闭按钮。\n");
        // sb.append("4.管理员用户新增在线审批功能。\n");
        Dialog dialog = new AlertDialog.Builder(Login.this)
                .setTitle("软件更新")
                .setMessage(sb.toString())
                // 设置内容
                .setPositiveButton("更新",// 设置确定按钮
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                pBar = new ProgressDialog(Login.this);
                                pBar.setTitle("正在下载");
                                pBar.setMessage(UpdateMessage);
                                pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                downFile(WSHelper.UPDATE_SERVER
                                        + WSHelper.UPDATE_APKNAME);
                            }

                        })
                .setNegativeButton("暂不更新",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int whichButton) {
                                // 点击"取消"按钮之后退出程序
                                finish();
                            }
                        }).create();// 创建
        // 显示对话框
        dialog.show();
    }

    // 下载文件
    void downFile(final String url) {
        pBar.show();
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);
                HttpResponse response;
                try {
                    response = client.execute(get);
                    HttpEntity entity = response.getEntity();
                    long length = entity.getContentLength();
                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {

                        File file = new File(
                                Environment.getExternalStorageDirectory(),
                                WSHelper.UPDATE_SAVENAME);
                        fileOutputStream = new FileOutputStream(file);

                        byte[] buf = new byte[1024];
                        int ch = -1;
                        int count = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            if (length > 0) {
                            }
                        }

                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                    downApk();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }.start();

    }

    // 下载后更新安装
    void downApk() {
        handler.post(new Runnable() {
            public void run() {
                pBar.cancel();
                update();
            }
        });
    }

    // 更新安装
    void update() {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), WSHelper.UPDATE_SAVENAME)),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

    // 登陆后事件
    private void down() {
        handler.post(new Runnable() {
            public void run() {
                try {
                    if (usr.DID != null) {
                        boolean isGo = true;
                        if (isApply.equals("0")) {
                            isGo = false;
                            PhoneInfo siminfo = new PhoneInfo(Login.this);
                            siminfo.getPhoneInfo();
                            siminfo.phone.Applicantid = usr.GH;
                            siminfo.phone.Applicantname = usr.DNAME;
                            siminfo.phone.Applystate = isApply;
                            JSONObject jobj = siminfo.phone.toJSONObject();
                            phone = WSHelper.InsertPhoneInfo(jobj.toString());
                            if (phone.Deviceid != null) {
                                isGo = true;
                                isApply = phone.Applystate;
                            } else {
                                final MultiDialog mydialog = new MultiDialog(
                                        Login.this,
                                        MultiDialog.DialogType.ALERT);
                                mydialog.setMessage("同步手机信息出错，请后重试！"
                                        + jobj.toString());
                                mydialog.show();
                                mDialog.cancel();
                            }
                        }
                        if (isGo) {
                            Toast tt = Toast.makeText(Login.this, "登录成功！用户为："
                                    + usr.DNAME, Toast.LENGTH_LONG);
                            tt.show();
                            tt.setGravity(Gravity.CENTER, 0, 0);

                            final Intent intent = new Intent(Login.this,
                                    SystemMain.class);
                            intent.putExtra("userinfo", usr);
                            intent.putExtra("isApply", isApply);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            Login.this.getApplicationContext().startActivity(
                                    intent);

                            mDialog.cancel();
                            // 记录登录
                            // WriteLoginHistory();
                            // Login.this.unregisterReceiver(loginReciever);

                            Login.this.finish();
                        }
                    } else {
                        Toast tt = Toast.makeText(Login.this, "登录失败：工号或者密码错误！",
                                Toast.LENGTH_LONG);
                        tt.show();
                        mDialog.cancel();
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    Log.v("Login", e.toString());
                }
            }
        });
    }

    /* 返回按键事件 */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // mDialog.cancel();
            System.exit(0);
            super.finish();
        }
        return false;
    }

    /* 关闭Activity并且退出系统时调用 */
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onPause()
     */
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub

        Login.this.unregisterReceiver(loginReciever);
        // System.exit(0);
        super.onPause();
    }

    /*
     * @see android.app.Activity#onRestart()
     */
    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        boolean state = false;
        state = IsUpdate();
        if (!state) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(BAR_READ_ACTION);
            filter.addAction(RFID_READ_ACTION);
            filter.addAction(INTENT_ACTION_SCAN_RESULT);
            filter.addAction(SCANACTION);
            filter.addAction(Neusoft);
            filter.addAction(NLSCAN_SCANNER);
            registerReceiver(loginReciever, filter);
        }
        super.onRestart();
    }

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BAR_READ_ACTION);
        filter.addAction(RFID_READ_ACTION);
        filter.addAction(INTENT_ACTION_SCAN_RESULT);
        filter.addAction(SCANACTION);
        filter.addAction(Neusoft);
        filter.addAction(NLSCAN_SCANNER);
        registerReceiver(loginReciever, filter);
        super.onResume();
    }

}
